package org.hu.controller;

import lombok.extern.slf4j.Slf4j;
import org.hu.entity.vo.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@CrossOrigin
@Slf4j
@RestController
public class UploadController {
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws Exception {
        log.info("文件上传:{}", image);
        //获取原始文件名
        String originalFilename = image.getOriginalFilename();

        //用uuid构造唯一文件名
        int index = originalFilename.lastIndexOf("."); //获取"."的下标
        String baseName = (index != -1) ? originalFilename.substring(0, index) : originalFilename; // 获取原始名
        String extname = originalFilename.substring(index); // 获取扩展名
        String newFileName = baseName + "-" + UUID.randomUUID() + extname;
        log.info("新文件名:{}", newFileName);

        String path = "D:/upload/";
        //将文件保存在服务器磁盘目录中
        image.transferTo(new File(path + newFileName));
        // 返回文件名
        return Result.success("上传成功", newFileName);
    }

}